package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"new/cache"
	"new/models"
	"new/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Register() {
	account := c.GetString("account")
	password := c.GetString("password")
	if account == "" || password == "" {
		res := Msg{
			Code: 0,
			Msg:  "用户名和密码不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	var user = models.User{
		Account:  account,
		Password: pkg.Md5(password),
	}
	if err := user.Username(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "参数错误",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if user.ID > 0 {
		res := Msg{
			Code: 0,
			Msg:  "用户已存在",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if err := user.Create(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res := Msg{
		Code: 200,
		Msg:  "注册成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	account := c.GetString("account")
	password := c.GetString("password")
	if account == "" || password == "" {
		res := Msg{
			Code: 0,
			Msg:  "用户名和密码不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	key := "password" + account
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		res := Msg{
			Code: 0,
			Msg:  "密码输入次数超过3次,封禁2小时",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	var user = models.User{
		Account:  account,
		Password: password,
	}
	if err := user.Username(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "参数错误",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		res := Msg{
			Code: 0,
			Msg:  "用户不存在,请前去注册",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		res := Msg{
			Code: 0,
			Msg:  "密码错误,请重新输入密码",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res := Msg{
		Code: 200,
		Msg:  "登录成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return
	cache.Rdb.Del(cache.Ctx, key)
}
